package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/*
* 菜品管理
* */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;


    @Autowired
    private RedisTemplate redisTemplate;




    /*
    * 新增菜品
    * */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);
        //新增菜品也需要清理该菜品分类下的缓存信息
        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");

        return R.success("新增菜品成功");

    }



    /*
    * 菜品信息分页查询
    * */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //构造分页构造器
        Page<Dish> pageInfo = new Page(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        lambdaQueryWrapper.like(name != null,Dish::getName,name)
                .orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo,lambdaQueryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> recodes = pageInfo.getRecords();
        List<DishDto> list = null;

        //利用stream流的方式处理(多用于两表之间数据的修改)
        List<DishDto> listed = recodes.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);


            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(listed);

        return R.success(dishDtoPage);
    }




    /*
    * 根据id查询菜品信息和对应的口味信息
    * */
    @GetMapping("/{id}")
    public R<DishDto> getId(@PathVariable Long id){

        log.info("需要查询的菜品id:{}",id);

        DishDto dishDto = dishService.getByIdWithFlavor(id);


        return R.success(dishDto);
    }



    /*
    * 修改菜品
    *
    * */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        //清理某个分类下面菜品的缓存数据
        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");


        return R.success("修改成功");
    }



    /*
    * 状态更新
    * */
    @PostMapping("/status/{status}")
    public R<String> dishStatusByStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        //更新条件
        Dish dish = new Dish();
        dish.setStatus(status);
        //更新对象
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Dish::getId,ids);
        //更新操作
        dishService.update(dish,lambdaQueryWrapper);
        return R.success("更新成功");
    }



    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Dish::getId,ids);

        dishService.remove(lambdaQueryWrapper);

        return R.success("删除成功");
    }




    /*
    * 根据条件查询对应的菜品数据
    * */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish){//定义Category来增加通用性
        //构造查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());

        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询起售状态的菜品
        lambdaQueryWrapper.eq(Dish::getStatus,1);

        List<Dish> dishes = dishService.list(lambdaQueryWrapper);

        return R.success(dishes);
    }*/



    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){//定义Dish来增加通用性

        List<DishDto> dishDtoList = null;

        //动态拼接key
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();


        //先从redis中获取缓存数据
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);

        if(dishDtoList != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }

        //构造查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());

        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询起售状态的菜品
        lambdaQueryWrapper.eq(Dish::getStatus,1);

        List<Dish> dishes = dishService.list(lambdaQueryWrapper);


        List<DishDto> listed = dishes.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);


            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper1);

            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoList = listed;
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到redis
        //你使用 redisTemplate.opsForValue() 方法时，可以将不同类型的数据作为值存储到 Redis 中
        redisTemplate.opsForValue().set(key,dishDtoList);

        return R.success(dishDtoList);
    }




}
